package Initialize

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commConfig"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEnv"
	"gitee.com/fierce_wolf/go-fox-edge-common/commLogger"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedis"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisStatus"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisTag"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
	"go-fox-edge-persist/entityAdapter"
	"go-fox-edge-persist/entityManager"
	"go-fox-edge-persist/entityUpdater"
	"go-fox-edge-persist/entityVerify"
	"go-fox-edge-persist/scheduler"
)

func Initialize() {
	// 设置环境变量
	commEnv.Service.ServiceType = "system"
	commEnv.Service.ServiceName = "persist-native"
	commEnv.Service.ModelType = "persist"
	commEnv.Service.ModelName = "persist"
	commEnv.Service.ApplicationName = "fox-edge-server-persist-native"
	commEnv.Service.AppPort = 9202
	commEnv.SetWorkPath(1)

	// 连接redis
	commRedis.ConnectRedis()

	// 检查连接状态：连接不上就通过panic退出吧
	ok := commRedis.TestConnect()
	if !ok {
		panic("连接redis失败:" + commRedis.Options.Addr)
	}

	commLogger.Info("------------- persist-native 初始化开始！-------------")

	// 注册会用到的实体
	edgeEntity.Register()

	// 启动状态线程
	commRedisStatus.Instance()
	commRedisStatus.Scheduler()

	// 初始化数据管理
	entityManager.Instance()
	entityManager.InitLoadEntity()

	// 比对mysql和redis的数据一致性
	entityVerify.Initialize()

	// 初始化配置参数
	commConfig.InitializeByFilePath("serverConfig", "serverConfig.json")

	commRedisTag.SaveMode = true
	commRedisTag.Scheduler()

	entityUpdater.DeviceHistoryAdapter = entityAdapter.DeviceHistoryAdapter
	entityUpdater.DeviceValueRecordAdapter = entityAdapter.ValueRecordAdapter
	entityUpdater.DeviceSequenceAdapter = entityAdapter.SequenceRecordAdapter
	entityUpdater.SyncEntity()

	// 启动数据同步线程
	entityManager.Scheduler()

	// 启动线程
	scheduler.DeviceHistoryAdapter = entityAdapter.DeviceHistoryAdapter
	scheduler.OperateRecordAdapter = entityAdapter.DeviceOperateAdapter
	scheduler.DeviceRecordAdapter = entityAdapter.DeviceRecordAdapter
	scheduler.DeviceSequenceAdapter = entityAdapter.SequenceRecordAdapter
	scheduler.DeviceValueRecordAdapter = entityAdapter.ValueRecordAdapter
	scheduler.Scheduler()

	commLogger.Info("------------- persist-native 初始化结束！-------------")
	commLogger.Info("------------- persist-native 驻留在后台！-------------")
	select {}
}
